<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import ElementPlus from 'element-plus'
import { getFeedbackdata, getFeedbackdatalike, getFeedbackDetail, delFeedback, adminResetPassword, editaccountNonLocked } from '../../api/api'
let total = ref(0)
let page = ref(1)
let pageSize = ref(10)
import EditFeedback from './EditFeedback.vue'
import DetailFeedback from './DetailFeedback.vue'
import { Decrypt, Encrypt } from '../../untils/passjs/security'
import { useRoute } from 'vue-router'
let route = useRoute()
onMounted(() => {
    console.log(window.window.location);
    getFeedback()
    myUserId.value = JSON.parse(localStorage.getItem('userdetail'))?.user?.userId
    const feedbackId = route.query.feedbackId
    if (feedbackId) {
        getFeedbackDetailById(feedbackId)
    }
})
async function getFeedbackDetailById(feedbackId) {
    if (!feedbackId) {
        return;
    }
    try {
    const res = await getFeedbackDetail(feedbackId)
    console.log(res);
    if (res.code == 200) {
        Object.assign(formlist, {
            feedbackId: res.data.feedbackId,
            feedbackTitle: res.data.feedbackTitle,
            feedbackContent: res.data.feedbackContent,
            type: '详情',
            createTime: res.data.createTime,
            currentUserId: res.data.currentUserId,
            userId: res.data.userId,
            progressStatus: res.data.progressStatus,
            currentNickName: res.data.currentNickName
        })
        changeType.value = "detail"

        dialogFormVisibleDetail.value = true
    } else {
        console.error('获取详情失败:', res.msg)
    }
    } catch (error) {
        console.error('请求出错:', error)
    }
}
let myUserId = ref(null)
// 定义的头部输入框的数据
let topdata = ref({
    feedbackTitle: "",
})
// 表格数据
let tableData = ref([])
// 获取管理员管理的数据
async function getFeedback() {
    try {
        let data = await getFeedbackdata(page.value, pageSize.value)
        console.log(data);
        if (data.code == 200) {
            total.value = data.total
            tableData.value = data.rows
        }
    } catch (error) {
        console.log(error);
    }
}
// 渲染状态的显示
let switchFlag = (flag) => {
    return flag == 0 ? true : false;
}
// 删除
let dianjiid = ref(0)
const dialogVisible = ref(false)
function del(val) {
    dianjiid.value = val.feedbackId
    dialogVisible.value = true
}
async function yesdel() {
    dialogVisible.value = false
    try {
        let res = await delFeedback(dianjiid.value);
        if (res.code == 200) {
            ElMessage.success(res.msg)
            getFeedback()
        }
    } catch (error) {
        console.log(error);
    }
}
// 遮罩层
let dialogFormVisible = ref(false)
let changeType = ref("")

const currentUser = ref({})
let dialogFormVisibleDetail = ref(false)

//  传递参数
let formlist = reactive({})
function add() {
    Object.assign(formlist, {
        feedbackTitle: "",
        feedbackContent: "",
        type: "新增",
    })
    console.log(formlist);
    dialogFormVisible.value = true
    console.log("新增操作");
    changeType.value = 'add'
}
async function edit(row) {
    let feedbackContentval;
    try {
        let res = await getFeedbackDetail(row.feedbackId)
        if (res.code == 200) {
            feedbackContentval = res.data.feedbackContent
        }
    } catch (error) {
        console.log(error);
    }
    Object.assign(formlist, {
        feedbackId: row.feedbackId,
        feedbackTitle: row.feedbackTitle,
        feedbackContent: feedbackContentval,
        type: "修改",
    })
    changeType.value = "update"
    dialogFormVisible.value = true
}
function closechange() {
    dialogFormVisible.value = false
    getFeedback()
}
let isSearching = ref(false);
async function adminlike() {
    console.log("模糊查询操作");
    isSearching.value = true;
    let { feedbackTitle } = topdata.value
    try {
        let res = await getFeedbackdatalike(feedbackTitle, page.value, pageSize.value)
        if (res.code == 200) {
            tableData.value = res.rows
            if (res.rows.length == 0) {
                return;
            }
            total.value = res.total
        }
    } catch (error) {
        console.log(error);
    }
}
function cancel() {
    console.log("重置操作");
    isSearching.value = false;
    topdata.value = {
        feedbackTitle: "",
    }
    page.value = 1
    getFeedback()
}
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    page.value = e
    if (isSearching.value) {
        try {
            await adminlike()
        } catch (error) {
            console.log(error);
        }
    } else {
        getFeedback()
    }
}
async function detailfun(row) {
    Object.assign(formlist, {
        type: "详情",
        feedbackId: row.feedbackId,
        feedbackTitle: row.feedbackTitle,
        currentNickName: row.currentNickName,
        feedbackContent: '',
        createTime: row.createTime,
        currentUserId: row.currentUserId,
        userId: row.userId,
        progressStatus: row.progressStatus,
    })
    dialogFormVisibleDetail.value = true
    changeType.value = "detail"
}
function closeDeatilfun() {
    dialogFormVisibleDetail.value = false
    getFeedback()
}
const hasPermission = (permission) => {
    const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
    if (permissions[0] == "*:*:*") {
        return true;
    }
    return permissions.includes(permission);
};
</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>Feedback Record</span>
            </div>
            <div class="cont">
                <div class="one">
                    <!-- 输入反馈记录标题 -->
                    <div class="select">
                        <el-input v-model="topdata.feedbackTitle" class="inp" style="width: 240px"
                            placeholder="Please enter the feedback title">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <el-button type="primary" @click="adminlike">query</el-button>
                    <el-button type="primary" @click="cancel">reset</el-button>
                </div>
                <div class="exp">
                    <div class="export-excel">
                        <el-button type="primary" @click="add()" v-if="hasPermission('system:feedback:add')">
                            <el-icon>
                                <FolderAdd />
                            </el-icon>Add Feedback Record
                        </el-button>
                    </div>
                </div>
                <div class="tab">
                    <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true"
                        @change="funchange(scope.row)" v-if="hasPermission('system:feedback:query')">
                        <el-table-column width="55">
                        </el-table-column>
                        <el-table-column property="feedbackTitle" label="title">
                            <template #default="scope">
                                <el-tooltip :content="scope.row.feedbackTitle" placement="top" effect="light">
                                    <span style="cursor: pointer;">
                                        {{
                                            scope.row.feedbackTitle && scope.row.feedbackTitle.length > 8
                                                ? scope.row.feedbackTitle.slice(0, 8) + '...'
                                                : scope.row.feedbackTitle
                                        }}
                                    </span>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                        <el-table-column property="nickName" label="Feedback person" />
                        <el-table-column property="currentNickName" label="Processing person" />
                        <el-table-column property="progressStatus" label="status">
                            <template #default="scope">
                                <span>{{ {
                                    0: 'end', 1: 'processing', 2: 'return', 3: 'not sent'
                                }[scope.row.progressStatus] }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="createTime" label="time" />
                        <el-table-column property="operate" label="operate" width="300">
                            <template #default="scope">
                                <span class="more-button" @click="detailfun(scope.row)" style="cursor: pointer;">
                                    detail
                                </span>
                                <span class="more-button" @click="edit(scope.row)" style="cursor: pointer;"
                                    v-if="scope.row.userId == myUserId && hasPermission('system:feedback:edit')">
                                    edit
                                </span>
                                <span class="more-button" @click="del(scope.row)" style="cursor: pointer;"
                                    v-if="hasPermission('system:feedback:remove') && scope.row.userId == myUserId">
                                    delete
                                </span>
                            </template>

                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                        <el-pagination background layout="prev, pager, next" :current-page='page'
                            :page-count="Math.ceil(total / pageSize)" style="text-align: end;"
                            @current-change="getCurrentPage" />
                    </div>
                    <el-dialog v-model="dialogVisible" title="delete" width="500">
                        <span>Are you sure you want to delete it</span>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible = false">cancel</el-button>
                                <el-button type="primary" @click="yesdel()">
                                    sure
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </div>
            </div>
        </div>
        <EditFeedback v-model:formlist="formlist" :changeType="changeType" :dialogFormVisible="dialogFormVisible"
            @close="closechange"></EditFeedback>
        <DetailFeedback v-model:formlist="formlist" :changeType="changeType"
            :dialogFormVisibleDetail="dialogFormVisibleDetail" @closeDetail="closeDeatilfun"></DetailFeedback>
    </div>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
            // .one {
            //     margin: 10px;
            //     display: flex;
            //     padding: 10px;

            //     div {
            //         margin-right: 20px;
            //     }
            // }
            .one {
                margin: 10px;
                display: flex;
                flex-wrap: wrap;
                gap: 12px;
                align-items: center;
                padding: 10px;
            }

            .select {
                display: flex;
                align-items: center;
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }
            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    /* 如果使用 scoped，需要添加 ::v-deep */
    ::v-deep .custom-modal {
        background-color: rgba(0, 0, 0, 0.5);
        /* 设置弹窗背景颜色为半透明 */
    }

    /* 或者更精确的定位 */
    ::v-deep .custom-modal .el-overlay {
        background-color: rgba(0, 0, 0, 0.8);
    }
}
</style>